<?php

namespace models;

//如
// 1. http://www.dianping.com/shop/59167499
use util\CommonUtil;

class DianPingSpider extends BaseSpider {

    // 初始化webUrl、apiUrl
    function __construct($url, $ua){
        $this->ua = $ua;
        $this->webUrl = $url;
        $url = explode('?',$url)[0];
        $id = 0;
        if(preg_match('/([0-9]+)/',$url,$matches)){
            $id = $matches[1];
        }
        if ($id != 0) {
            $this->apiUrl = "http://www.dianping.com/shop/{$id}/review_more?pageno=1";
        }

    }

    // 获取评论列表，仅处理10条
    public function getComments(){

        if (empty($this->apiUrl)) return [];

        $ch = curl_init();
        $timeout = 30;
        curl_setopt ($ch, CURLOPT_URL, $this->apiUrl);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, $this->ua);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $file_contents = curl_exec($ch);
        curl_close($ch);
        if(empty($file_contents)) return;
        $html = str_get_html($file_contents);
        $liList = $html->find('div[class=comment-list] ul li');
        $num = 0;
        $arr = array();
        foreach($liList as $li){
            if($num < 10 && count($li->find('a[class=J_card] img')) != 0){
                $num ++;
                $obj = array();
                $obj['head'] = CommonUtil::replace2https($li->find('a[class=J_card] img')[0]->attr['src']);//头像
                $obj['nickname'] = $li->find('p[class=name] a')[0]->innertext;//昵称
                $obj['content'] = $li->find('div[class=J_brief-cont]')[0]->innertext;//评论内容
                //-----------------评论图片
                $picList = $li->find('a[class=thumb] img');
                $img_list_str_spider = '';
                for($i = 0;$i<count($picList);$i++){
                    $img = $picList[$i]->attr['src'];
                    $img_list_str_spider =  $img_list_str_spider. $img;
                    if ($i != count($picList) - 1) {
                        $img_list_str_spider = $img_list_str_spider . ',';
                    }
                }
                $obj['pic_urls'] = $img_list_str_spider;
                //-------------------
                $obj['reply'] = CommonUtil::checkReply($li->find('div[class=busi-reply] p')[0]->innertext);//商家回复
                $obj['comment_time'] = CommonUtil::checkTime($li->find('span[class=time]')[0]->innertext);//评论时间
                $arr[] = $obj;
            }
        }
        return $arr;

    }
	
}